<template>
  <div class="job-posting-container">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <h2>发布招聘信息</h2>
          <p>填写详细的职位信息，吸引优秀人才</p>
        </div>
      </template>

      <el-form ref="formRef" :model="jobForm" :rules="formRules" label-width="120px" class="job-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>

          <el-form-item label="职位标题" prop="title">
            <el-input v-model="jobForm.title" placeholder="请输入职位标题，如：Java后端开发工程师" maxlength="50" show-word-limit />
          </el-form-item>

          <el-form-item label="公司名称" prop="company">
            <el-input v-model="jobForm.company" placeholder="请输入公司名称" maxlength="50" />
          </el-form-item>

          <el-form-item label="工作类型" prop="jobType">
            <el-select v-model="jobForm.jobType" placeholder="请选择工作类型" style="width: 100%">
              <el-option label="全职" value="fulltime" />
              <el-option label="兼职" value="parttime" />
              <el-option label="实习" value="internship" />
              <el-option label="远程" value="remote" />
            </el-select>
          </el-form-item>

          <el-form-item label="工作地点" prop="location">
            <el-input v-model="jobForm.location" placeholder="请输入工作地点，如：北京·朝阳区" />
          </el-form-item>

          <el-form-item label="薪资范围" prop="salaryRange">
            <el-input v-model="jobForm.salaryRange" placeholder="请输入薪资范围，如：18K-30K" />
          </el-form-item>
        </div>

        <!-- 职位要求 -->
        <div class="form-section">
          <h3 class="section-title">职位要求</h3>

          <el-form-item label="学历要求" prop="education">
            <el-select v-model="jobForm.education" placeholder="请选择学历要求" style="width: 100%">
              <el-option label="不限" value="不限" />
              <el-option label="大专" value="大专" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </el-form-item>

          <el-form-item label="工作经验" prop="experience">
            <el-select v-model="jobForm.experience" placeholder="请选择工作经验要求" style="width: 100%">
              <el-option label="不限" value="不限" />
              <el-option label="应届生" value="应届生" />
              <el-option label="1-3年" value="1-3年" />
              <el-option label="3-6年" value="3-6年" />
              <el-option label="6-10年" value="6-10年" />
              <el-option label="10年以上" value="10年以上" />
            </el-select>
          </el-form-item>

          <el-form-item label="技能标签" prop="tags">
            <div class="tags-input">
              <el-tag v-for="tag in jobForm.tags" :key="tag" closable @close="removeTag(tag)" class="tag-item">
                {{ tag }}
              </el-tag>
              <el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" class="tag-input" />
              <el-button v-else size="small" @click="showInput">+ 添加技能</el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 职位描述 -->
        <div class="form-section">
          <h3 class="section-title">职位描述</h3>

          <el-form-item label="工作职责" prop="responsibilities">
            <el-input v-model="jobForm.responsibilities" type="textarea" :rows="4" placeholder="请详细描述工作职责和内容..." maxlength="1000" show-word-limit />
          </el-form-item>

          <el-form-item label="任职要求" prop="requirements">
            <el-input v-model="jobForm.requirements" type="textarea" :rows="4" placeholder="请详细描述任职要求和技能要求..." maxlength="1000" show-word-limit />
          </el-form-item>
        </div>

        <!-- 联系信息 -->
        <div class="form-section">
          <h3 class="section-title">联系信息</h3>

          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="jobForm.contactPerson" placeholder="请输入联系人姓名" />
          </el-form-item>

          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="jobForm.phone" placeholder="请输入联系电话" />
          </el-form-item>

          <el-form-item label="公司头像">
            <el-upload class="avatar-uploader" action="#" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="handleAvatarUpload">
              <img v-if="jobForm.face" :src="jobForm.face" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <el-form-item class="submit-section">
          <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> 发布职位 </el-button>
          <el-button size="large" @click="resetForm">重置</el-button>
          <el-button size="large" @click="previewJob">预览</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="职位预览" width="600px">
      <div class="job-preview">
        <div class="preview-header">
          <img v-if="jobForm.face" :src="jobForm.face" class="preview-avatar" />
          <div class="preview-info">
            <h3>{{ jobForm.title || '职位标题' }}</h3>
            <p>{{ jobForm.company || '公司名称' }}</p>
          </div>
        </div>
        <div class="preview-details">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="薪资">{{ jobForm.salaryRange || '-' }}</el-descriptions-item>
            <el-descriptions-item label="地点">{{ jobForm.location || '-' }}</el-descriptions-item>
            <el-descriptions-item label="经验">{{ jobForm.experience || '-' }}</el-descriptions-item>
            <el-descriptions-item label="学历">{{ jobForm.education || '-' }}</el-descriptions-item>
          </el-descriptions>
          <div v-if="jobForm.tags.length" class="preview-tags">
            <el-tag v-for="tag in jobForm.tags" :key="tag" class="tag-item">{{ tag }}</el-tag>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'

// 表单数据类型定义
interface JobForm {
  title: string
  company: string
  jobType: string
  tags: string[]
  location: string
  salaryRange: string
  responsibilities: string
  requirements: string
  contactPerson: string
  phone: string
  education: string
  experience: string
  face: string
}

// 表单引用
const formRef = ref<FormInstance>()
const inputRef = ref()

// 表单数据
const jobForm = reactive<JobForm>({
  title: '',
  company: '',
  jobType: '',
  tags: [],
  location: '',
  salaryRange: '',
  responsibilities: '',
  requirements: '',
  contactPerson: '',
  phone: '',
  education: '',
  experience: '',
  face: ''
})

// 标签输入相关
const inputVisible = ref(false)
const inputValue = ref('')

// 状态管理
const submitting = ref(false)
const previewVisible = ref(false)

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: '请输入职位标题', trigger: 'blur' },
    { min: 2, max: 50, message: '职位标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  jobType: [{ required: true, message: '请选择工作类型', trigger: 'change' }],
  location: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
  salaryRange: [{ required: true, message: '请输入薪资范围', trigger: 'blur' }],
  requirements: [{ required: true, message: '请输入任职要求', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  education: [{ required: true, message: '请选择学历要求', trigger: 'change' }],
  experience: [{ required: true, message: '请选择工作经验要求', trigger: 'change' }]
}

// 添加标签
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !jobForm.tags.includes(inputValue.value)) {
    jobForm.tags.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const removeTag = (tag: string) => {
  const index = jobForm.tags.indexOf(tag)
  if (index > -1) {
    jobForm.tags.splice(index, 1)
  }
}

// 头像上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = (options: any) => {
  // 这里模拟上传，实际项目中需要调用真实的上传接口
  const reader = new FileReader()
  reader.onload = (e) => {
    jobForm.face = e.target?.result as string
  }
  reader.readAsDataURL(options.file)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    const submitData = {
      ...jobForm,
      tagsJson: JSON.stringify(jobForm.tags),
      postedDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
      createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      status: 'active',
      id: Date.now().toString()
    }

    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1500))

    ElMessage.success('职位发布成功！')
    console.log('提交的数据:', submitData)
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要重置表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value?.resetFields()
    jobForm.tags = []
    jobForm.face = ''
    ElMessage.success('表单已重置')
  })
}

// 预览职位
const previewJob = () => {
  if (!jobForm.title || !jobForm.company) {
    ElMessage.warning('请至少填写职位标题和公司名称')
    return
  }
  previewVisible.value = true
}
</script>

<style scoped>
.job-posting-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.job-form {
  margin-top: 20px;
}

.form-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.submit-section {
  text-align: center;
  margin-top: 40px;
}

.submit-section .el-button {
  margin: 0 8px;
  min-width: 120px;
}

/* 预览样式 */
.job-preview {
  padding: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-avatar {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
}

.preview-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.preview-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.preview-details {
  margin-top: 16px;
}

.preview-tags {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .job-posting-container {
    padding: 16px;
  }

  .job-form :deep(.el-form-item__label) {
    width: 100px !important;
  }

  .tags-input {
    flex-direction: column;
    align-items: flex-start;
  }

  .submit-section .el-button {
    margin: 4px;
    min-width: 100px;
  }
}
</style>
